#ifndef TCPMGR_H
#define TCPMGR_H

#include"singleton.hpp"
#include"global.h"
#include <QObject>
#include<QWebSocket>

class TcpMgr:public QObject, public Singleton<TcpMgr>
{
    friend class Singleton<TcpMgr>;
    Q_OBJECT
public:
    ~TcpMgr();
    void Close();
    bool isConnected() const;

private:
    TcpMgr();
    void initHandlers();
    void handleMsg(const ReqId id, const QByteArray &data) const;

public slots:
    void slot_tcp_onnect(const ServerInfo &);
    void slot_send_data(ReqId reqId, QByteArray  data);
    void slot_ready_read(const QByteArray &message);
    void slot_disconnected();

signals:
    void sig_con_success(bool);
    void sig_send_data(ReqId, QByteArray);
    void sig_login_failed(bool);
    void sig_search_user(int);
    void sig_add_friend_req(const QString&, const QString&);
    void sig_add_text_msg(const QString&, const QString&);

private:
    QWebSocket _socket;
    QString _host{""};
    uint _port{0};
    QByteArray _buffer{};
    bool _isPending{false};
    quint16 _messageId{0};
    quint16 _messageLen{0};
    bool _isReconnection{true};

    std::map<ReqId, std::function<void(const QJsonObject&)>> _handlers{};
};

#endif // TCPMGR_H
